window.layModules = {};

var urls = {
    returnUrl: '/front/redirect/return'
};

function LoginForm() {
    this.init();
}

LoginForm.prototype = {
    init: function () {
        $('#login-form').on('submit', function (e) {
            e.preventDefault();
            var account = this.account.value;
            var password = this.password.value;
            var remember = this.remember.value;

            var loadingIndex = layModules.layer.load(1);
            $.post('/front/user/_login', {account: account, password: password, remember: remember}, function (res) {
                layModules.layer.close(loadingIndex);
                if (res.code === 0) {
                    layModules.layer.msg('登陆成功');
                    setTimeout(function () {
                        window.location.href = urls.returnUrl;
                    }, 1000);
                } else {
                    layModules.layer.msg(res.msg);
                }
            }, 'json');
            return false;
        });
    }
};

function StatusChecker() {
    this.init();
}

StatusChecker.prototype = {
    init: function () {

    },
    check: function (cb) {
        this.checkAuthorization();
    },
    checkAuthorization: function (cb) {
        $.get('/front/authorization/current', function (res) {
            console.log(res);
            if (res.code === 0) {
                window.location.href = urls.returnUrl;
            } else {
                layModules.layer.msg(res.msg);
            }
        }, 'json');
    }
};

$(function () {
    var onPlatformReady = function () {
        var checker = new StatusChecker();
        checker.check(function (r) {
            if (r) {
                //检查通过，初始化Dom
                new LoginForm();
            } else {
                window.location.href = urls.returnUrl;
            }
        });
        new LoginForm();
    };
    layui.use(['form', 'layer', 'element'], function () {
        layModules.from = layui.from;
        layModules.layer = layui.layer;
        layModules.element = layui.element;
        onPlatformReady();
    });
});